
//清空代码函数
function CodeClear(i) {
    if(i === 0) {
        swal({
            title: "你确定吗?",
            text: "你写的所有代码将会被删除",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "确定"
        }, function () {
            editor.setValue("");
        });
    } else {
        editor.setValue("");
    }
}

function look(email) {
    window.location = "LookOtherUser.html?user="+email;
}

//提交代码给后台
function CodeSubmit() {
    var fightUser, language, code;
    fightUser = $('input[name="challenge"]:checked').val();
    language = $("#languageSelect").val();
    language = language.substring(0,language.indexOf("("));
    code = editor.getValue();
    let postData = {};
    postData['fightUser'] = fightUser;
    postData['language'] = language;
    postData['code'] = code;
    postData['userToken'] = localStorage.getItem("userToken");
    if(!fightUser)
        swal("错误","请选择你的挑战对象","error");
    else if(code === "")
        swal("错误","提交代码不能为空","error");
    else {
        $.ajax({
            async: true,
            type: "post",
            url: serverIpAddress+"CodeGame/SaveRunCode",
            contentType: "application/json;charset=utf-8",
            data: JSON.stringify(postData),
            success:function (data) {
                //此处返回字符串"Blocked by Sentinel (flow limiting)"，被Sentinel流控
                if(data=="Blocked by Sentinel (flow limiting)") {
                    swal("错误","当前为代码提交高峰期，请稍后再试","error");
                }
                else {//提交成功
                    swal("提交成功", "请稍后在提交列表中查看评测结果！", "success");
                    CodeClear(1);
                }
            }
        });
    }
}


function changePages(position) {//0表示左滚动一页，1表示右滚动一页
    var a, soon = document.getElementById("pageOne").innerText;
    var first = Number(soon);
    if(position === 0)
        a = -1;
    else
        a = 1;
    if(first !== 1 && first + 4 !== UserTable.length) {
        document.getElementById("pageOne").innerHTML = "<a href=\"\" href='javascript:LodeUserTable(\"" + (first + a).toString() + "#One\")'>" + (first + a).toString() + "</a>";
        document.getElementById("pageTwo").innerHTML = "<a href=\"\" href='javascript:LodeUserTable(\"" + (first + a + 1).toString() + "#Two\")'>" + (first + a + 1).toString() + "</a>";
        document.getElementById("pageThree").innerHTML = "<a href=\"\" href='javascript:LodeUserTable(\"" + (first + a + 2).toString() + "#Three\")'>" + (first + a + 2).toString() + "</a>";
        document.getElementById("pageFour").innerHTML = "<a href=\"\" href='javascript:LodeUserTable(\"" + (first + a + 3).toString() + "#Four\")'>" + (first + a + 3).toString() + "</a>";
        document.getElementById("pageFive").innerHTML = "<a href=\"\" href='javascript:LodeUserTable(\"" + (first + a + 4).toString() + "#Five\")'>" + (first + a + 4).toString() + "</a>";
    }
}

SetUserTableValue();
LodeUserTable("1#One");

var UserTable, NowPage = "One";

function SetUserTableValue() {
    $.ajax({
        async: false,
        type: "post",
        url: serverIpAddress+"CodeGame/LodeUserTable",
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        success: function (data) {
            UserTable = data;
        }
    });
}

function LodeUserTable(soon) {
    $("#page"+NowPage).removeClass("active");
    NowPage = soon.substring(soon.indexOf("#")+1);
    $("#page"+NowPage).addClass("active");

    soon = soon.substring(0,soon.indexOf("#"));
    var tag = Number(soon);
    tag = tag - 1;
    var i, code = "<thead><tr><td>排名</td><td><b>姓名</b></td><td><b>战绩</b></td><td><b>&nbsp;&nbsp;&nbsp;查看</b></td><td><b>选择</b></td></tr></thead>", j;
    var bodyOne = "<tbody><tr><td><b>&nbsp;", bodyTwo = "</b></td><td>";
    var bodyThree = "</td><td>", bodyFour = "</td><td><button class='btn btn-info' style='border-radius: 6px;background-color: skyblue;border-color: skyblue;color: white;' onclick='look(\"";
    var bodyFive = "\")'>查看</button></td><td>&nbsp;",bodySix = "<input type='radio' name='challenge' value='";
    var bodySeven = "'></td></tr></tbody>";
    for(i = tag*5, j = 0; i < UserTable.length && j < 5; i++,j++) {
        code += bodyOne+(i+1).toString()+bodyTwo+UserTable[i].name+bodyThree+(UserTable[i].rankFractions
            *100+"%")+bodyFour+UserTable[i].userEmail+bodyFive+bodySix+UserTable[i].userEmail+bodySeven;
    }

    document.getElementById("UserTable").innerHTML = code;
}

$("#mybody").css("height",$(this).height()-80+"px");
$("#area1").val("1");
$("#area2").val("");
$(window).resize(function() {
    var myheight = $(this).height();
    $("#mybody").css("height",myheight-80+"px");
});
$("#area2").keyup(function(){
    var length=$("#area2").val().split("\n").length;
    var temp=""
    var wid=0;
    for(var i=1;i<=length;i++) {
        temp=temp+i+"\n";
    }
    while(length>=10) {
        length/=10;
        wid++;
    }
    $("#area1").css("width",2+wid+"%");
    $("#area2").css("width",98-wid+"%");
    $("#area1").val(temp);
});

$("#area2").keydown(function(e){
    if (e.which == 57 && e.shiftKey) {
        $("#area2").val($("#area2").val()+"()");
        return false;
    }
    else if (e.which == 219 && e.shiftKey) {
        $("#area2").val($("#area2").val()+"{}");
        return false;
    }
    else if (e.which == 219) {
        $("#area2").val($("#area2").val()+"[]");
        return false;
    }
    else if (e.which == 188 && e.shiftKey) {
        $("#area2").val($("#area2").val()+"<>");
        return false;
    }
});
function myscroll() {
    $("#area1").scrollTop($("#area2").scrollTop());
}

// JavaScript Document
var canvas = document.getElementById("cas");

var ctx = canvas.getContext("2d");
resize();

window.onresize = resize;




function resize() {

    canvas.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;

    canvas.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

}




var RAF = (function() {

    return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) {

        window.setTimeout(callback, 1000 / 60);

    };

})();




// 鼠标活动时，获取鼠标坐标

var warea = {x: null, y: null, max: 20000};

window.onmousemove = function(e) {

    e = e || window.event;




    warea.x = e.clientX;

    warea.y = e.clientY;

};

window.onmouseout = function(e) {

    warea.x = null;

    warea.y = null;

};




// 添加粒子

// x，y为粒子坐标，xa, ya为粒子xy轴加速度，max为连线的最大距离

var dots = [];

for (var i = 0; i < 300; i++) {

    var x = Math.random() * canvas.width;

    var y = Math.random() * canvas.height;

    var xa = Math.random() * 2 - 1;

    var ya = Math.random() * 2 - 1;




    dots.push({

        x: x,

        y: y,

        xa: xa,

        ya: ya,

        max: 6000

    })

}




// 延迟100秒开始执行动画，如果立即执行有时位置计算会出错

setTimeout(function() {

    animate();

}, 100);




// 每一帧循环的逻辑

function animate() {

    ctx.clearRect(0, 0, canvas.width, canvas.height);




    // 将鼠标坐标添加进去，产生一个用于比对距离的点数组

    var ndots = [warea].concat(dots);




    dots.forEach(function(dot) {




        // 粒子位移

        dot.x += dot.xa;

        dot.y += dot.ya;




        // 遇到边界将加速度反向

        dot.xa *= (dot.x > canvas.width || dot.x < 0) ? -1 : 1;

        dot.ya *= (dot.y > canvas.height || dot.y < 0) ? -1 : 1;




        // 绘制点

        ctx.fillRect(dot.x - 0.5, dot.y - 0.5, 1, 1);




        // 循环比对粒子间的距离

        for (var i = 0; i < ndots.length; i++) {

            var d2 = ndots[i];




            if (dot === d2 || d2.x === null || d2.y === null) continue;




            var xc = dot.x - d2.x;

            var yc = dot.y - d2.y;




            // 两个粒子之间的距离

            var dis = xc * xc + yc * yc;




            // 距离比

            var ratio;




            // 如果两个粒子之间的距离小于粒子对象的max值，则在两个粒子间画线

            if (dis < d2.max) {




                // 如果是鼠标，则让粒子向鼠标的位置移动

                if (d2 === warea && dis > (d2.max / 2)) {

                    dot.x -= xc * 0.03;

                    dot.y -= yc * 0.03;

                }




                // 计算距离比

                ratio = (d2.max - dis) / d2.max;




                // 画线

                ctx.beginPath();

                ctx.lineWidth = ratio / 2;

                ctx.strokeStyle = 'rgba(0,0,0,' + (ratio + 0.2) + ')';

                ctx.moveTo(dot.x, dot.y);

                ctx.lineTo(d2.x, d2.y);

                ctx.stroke();
            }
        }

        // 将已经计算过的粒子从数组中删除
        ndots.splice(ndots.indexOf(dot), 1);
    });
    RAF(animate);
}


